const ws = require("nodejs-websocket");
let count = 0;
const server = ws.createServer((connect) => {
  console.log("有用户连接上来了");
  count++;
  connect.userName = `用户${count}`;
  broadcast(`${connect.userName}进入了聊天室`);
  connect.on("text", (data) => {
    broadcast(`${connect.userName}:${data}`);
  });
  connect.on("close", () => {
    broadcast(`${connect.userName}离开了聊天室`);
    count--;
  });
  connect.on("error", () => {
    console.log("用户连接异常");
  });
});

function broadcast(msg) {
  server.connections.forEach((item) => {
    item.send(msg);
  });
}

server.listen(8080, () => {
  console.log("websocket服务启动成功了,监听了端口3000");
});
